package pl.nazaweb.jboot.walking;

import java.io.File;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import pl.nazaweb.jboot.utils.FileWriterUtils;

/**
 *
 * @author naza
 */
public class WalkinListenerThread extends Thread implements NativeKeyListener {
    
    private int walkingMap[][] = new int[1000][1000];
    private int xCurrentPosition = 500;
    private int yCurrentPosition = 500;
    
    @Override
    public void run() {
        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            System.err.println(ex.getMessage());
            throw new RuntimeException("There was a problem registering the native hook.");
        }
        walkingMap[xCurrentPosition][yCurrentPosition] = 1;
        GlobalScreen.getInstance().addNativeKeyListener(new WalkinListenerThread());
        while (GlobalScreen.isNativeHookRegistered()) {
        }        
    }
    
    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
        switch (e.getKeyCode()) {
            case NativeKeyEvent.VK_UP: {
                yCurrentPosition++;
                break;
            }
            case NativeKeyEvent.VK_DOWN: {
                yCurrentPosition--;
                break;
            }
            case NativeKeyEvent.VK_RIGHT: {
                xCurrentPosition++;
                break;
            }
            case NativeKeyEvent.VK_LEFT: {
                xCurrentPosition--;
                break;
            }
        }
        if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE) {
            GlobalScreen.unregisterNativeHook();
            writeWalkingMapToFile();
        }
        walkingMap[xCurrentPosition][yCurrentPosition] = 1;
        System.out.println(String.format("x=%s, y=%s", xCurrentPosition, yCurrentPosition));
    }
    
    private void writeWalkingMapToFile() {
        FileWriterUtils.writeAllArray(walkingMap, new File("c:\\mapa.jbot"));
    }
    
    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
        //System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }
    
    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
        //System.out.println("Key Typed: " + e.getKeyText(e.getKeyCode()));
    }
}
